package billing;

import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.Set;

/**
 * used internally to Store bill data
 * @author Gernot
 *
 */
public class BillData {
    private HashMap<Long,Double> auctions = new HashMap<Long,Double>();
    
    /**
     * does not check for errors
     * @param id
     * @param price
     */
    public void addAuction(long id, double price){
        auctions.put(id, price);
    }
    
    public Bill createBill(PriceSteps pricing){
        StringBuilder sb = new StringBuilder();
        
        Set<Long> ids = auctions.keySet();
        
        for (long id:ids){
            //sb.append(id).append("\t");
            sb.append(stringFixLength(Long.toString(id), 11));
            calculateBill(auctions.get(id), pricing, sb);
            sb.append("\n");
        }
                
        return new Bill(sb.toString());
    }
        
    private static void calculateBill(double p, PriceSteps ps, StringBuilder sb){
        //find correct priceStep
        
        PriceStep matching_ps = null;
        for (PriceStep step: ps.getSteps()){
            if (step.isInIntervall(p)){
                matching_ps = step;
                break;
            }
        }
        
        if (matching_ps == null){
            //TODO: correct error handling
            //sb.append(p).append("\t").append("NO_MATCHING_PRICE_STEP");
            sb.append(stringFixLength(doubleToStrF(p, 2), 13));
            sb.append("NO_MATCHING_PRICE_STEP");
        } else {
            //sb.append(p).append("\t");
            sb.append(stringFixLength(doubleToStrF(p, 2), 13));
            double var = p*matching_ps.getVarialePriceDouble();
            double fix = matching_ps.getFixedPrice(); 
            //sb.append(fix).append("\t");
            sb.append(stringFixLength(doubleToStrF(fix, 2), 10));
            //sb.append(var).append("\t");
            sb.append(stringFixLength(doubleToStrF(var, 2), 13));
            //sb.append(fix+var);
            sb.append(doubleToStrF(fix+var, 2));
        }
    }
    
    
    

	
	private static String doubleToStrF(double d, int decimalPlaces) {
		StringBuilder pattern = new StringBuilder("0.");
		for (int i = 0; i < decimalPlaces; i++) {
			pattern.append('#');
		}
		DecimalFormat dec = new DecimalFormat(pattern.toString());
		return dec.format(d);
	}
	
	private static String stringFixLength(String s, int length) {
		StringBuilder sb = new StringBuilder(s);
		for (int i = s.length(); i < length; i++) {
			sb.append(' ');
		}
		return sb.toString();
	}
}
